<?php
/**
 * This file is part of the UXLabs project.
 *
 * (c) UXLabs project <http://code.uxlabs.me>
 *
 */

namespace uxl\app\api\models;

use yii\db\ActiveRecord;
use yii\db\Query;

/**
 * app api访问授权
 *
 * @property int $id AUTO_INCREMENT
 * @property int $tokenId app api接口app授权ID
 * @property string $accessKey 访问授权密钥
 * @property string $secretKey 访问加密密钥
 * @property int $expiresIn 过期时间，0-不过期，单位：分钟
 * @property string $clientType 客户端类型
 * @property string $clientInfo 授权的客户端信息
 * @property int $status 状态，1-有效
 * @property string $createAt
 *
 * @package uxl\app\api\models
 * @author ice deng <ice.deng@qq.com>
 */
class AccessToken extends ActiveRecord
{
    /** @inheritdoc */
    public static function tableName()
    {
        return '{{%app_api_access_token}}';
    }

    /**
     * 添加授权密钥
     * @param $tokenId
     * @param $accessKey
     * @param $secretKey
     * @param int $expiresIn
     * @param $clientType
     * @param string $clientInfo
     * @return mixed
     */
    public function appendKey($tokenId, $accessKey, $secretKey, $expiresIn = 0, $clientType, $clientInfo = '')
    {
        $row = new static();
        $row->tokenId = $tokenId;
        $row->accessKey = $accessKey;
        $row->secretKey = $secretKey;
        $row->expiresIn = $expiresIn;
        $row->clientType = $clientType;
        $row->clientInfo = $clientInfo;
        return $row->save(false);
    }

    /**
     * 通过访问密钥获取授权记录
     * @param $accessKey
     * @return array|bool
     */
    public function getByAccessKey($accessKey)
    {
        $q = new Query();
        return $q->from(static::tableName())
            ->select('id, tokenId, accessKey, secretKey, expiresIn, status, NOW() - createAt AS t')
            ->where([
                'accessKey' => $accessKey,
            ])
            ->one();
    }
}

/**
 * CREATE TABLE IF NOT EXISTS `uxlabs_tpl_base`.`app_api_access_token` (
 * `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
 * `tokenId` INT NOT NULL COMMENT 'app api接口app授权ID',
 * `accessKey` CHAR(32) NOT NULL COMMENT '访问授权密钥',
 * `secretKey` CHAR(32) NOT NULL COMMENT '访问加密密钥',
 * `expiresIn` INT NOT NULL DEFAULT 0 COMMENT '过期时间，0-不过期，单位：分钟',
 * `clientType` VARCHAR(20) NULL COMMENT '客户端类型',
 * `clientInfo` VARCHAR(2000) NULL COMMENT '授权的客户端信息',
 * `status` SMALLINT NOT NULL DEFAULT 1 COMMENT '状态，1-有效',
 * `createAt` TIMESTAMP NOT NULL DEFAULT NOW(),
 * PRIMARY KEY (`id`),
 * INDEX `fk_app_api_access_token_app_api_token_idx` (`tokenId` ASC),
 * UNIQUE INDEX `ix_app_api_access_token_key` (`accessKey` ASC),
 * CONSTRAINT `fk_app_api_access_token_app_api_token`
 * FOREIGN KEY (`tokenId`)
 * REFERENCES `uxlabs_tpl_base`.`app_api_token` (`id`)
 * ON DELETE NO ACTION
 * ON UPDATE NO ACTION)
 * ENGINE = InnoDB
 * COMMENT = 'app api访问授权'
 */